package net.hashcoding.cookbook.core.controller;

import net.hashcoding.cookbook.core.ServiceException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;

/**
 * Created by Administrator on 2017/6/25.
 */
public class ControllerInterface implements Iterable<ControllerInterface.Parameter> {
    private String target;
    private Method method;

    private Parameter [] parameters;

    public ControllerInterface(String target, Method method, Parameter [] parameters) {
        this.target = target;
        this.method = method;
        this.parameters = parameters;
    }

    public Object invoke(Object object, Object ...args) {
        try {
            return method.invoke(object, args);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            throw ServiceException.internalError();
        }
    }

    public int lengthOfParameters() {
        return parameters.length;
    }

    @Override
    public Iterator<Parameter> iterator() {
        return new ParameterIterator(parameters);
    }

    public class ParameterIterator implements Iterator<Parameter> {

        private int idx = 0;
        private Parameter [] parameters;

        public ParameterIterator(Parameter [] parameters) {
            this.parameters = parameters;
            this.idx = 0;
        }

        @Override
        public boolean hasNext() {
            return idx < parameters.length;
        }

        @Override
        public Parameter next() {
            return parameters[idx++];
        }
    }

    public static class Parameter {
        String name;
        java.lang.reflect.Parameter parameter;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Parameter(String name, java.lang.reflect.Parameter parameter) {
            this.name = name;
            this.parameter = parameter;
        }
    }
}
